package cn.djx.springsecurity.config;

import cn.djx.springsecurity.utils.ResponseResult;
import cn.djx.springsecurity.utils.WebUtils;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
        /**
     * 当用户认证失败时执行的处理方法
     *
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @param authException 认证异常信息
     * @throws IOException IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 构建认证失败的响应结果
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "用户认证失败，请重新登录！");
        String json = JSON.toJSONString(result);
        // 将响应结果以JSON格式返回给前端
        WebUtils.renderString(response, json);
    }

}
